﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class UsageReportsForm : Form
    {
        enum ReportType { UseMechWork, UseHandWork, UseSeed, UseFertilizer, UseProtection, UseWater };
        int regID, avpID, fhID, pfshID = -1, cultID = -1, paramID;
        ReportType repType;
        const string catFertilizer = "Fertilizer", catTechniqe = "TechKind", catOperation = "OperationKind", catTechTool = "TechToolKind", catDimension = "Dimension";
        RESP_IIWaterAssessment.Entity.RESP_addDataContext resp_data = new RESP_IIWaterAssessment.Entity.RESP_addDataContext(DBClass.RESPContext.Connection);
        string[] repName = new string[] 
        { 
            "Использование механизированного труда в ПФШ",
            "Использование ручного труда в ПФШ",
            "Использование семян в ПФШ",
            "Использование Удобрений в ПФШ",
            "Использование средств зашиты в ПФШ",
            "Использование воды в ПФШ"
        };

        string[] repNameUzb = new string[] 
        { 
            "Механизациялашган меҳнат",
            "Қўл меҳнати",
            "Уруғ ишшлатилиши",
            "Ўғитлар қўллаш",
            "Ҳимоя воситаларини қўллаш",
            "Далада сувдан фойдаланиш"
        };

        public UsageReportsForm()
        {
            InitializeComponent();
        }

        private void UsageReportsForm_Load(object sender, EventArgs e)
        {
            if (InformationClass.Lang)
                cbReport.Items.AddRange(repName);
            else
                cbReport.Items.AddRange(repNameUzb);


            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            cbCulture.SelectedIndexChanged -= cbCulture_SelectedIndexChanged;
            cbCulture.DataSource = UtilClass.GetCBCultureDataSourse();
            cbCulture.DisplayMember = "Name";
            cbCulture.ValueMember = "ID";
            cbCulture.SelectedIndex = -1;
            cbCulture.SelectedIndexChanged += new EventHandler(cbCulture_SelectedIndexChanged);


            groupBoxParam.Visible = false;
        }

        private void cbReport_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbReport.SelectedIndex >= 0)
                repType = (ReportType)cbReport.SelectedIndex;

            groupBoxParam.Visible = true;

            cbParam.SelectedIndexChanged -= cbParam_SelectedIndexChanged;
            cbParam.DataSource = null;
            switch (repType)
            {
                case ReportType.UseSeed:
                    groupBoxParam.Visible = true;
                    if (InformationClass.Lang)
                        chbParam.Text = "Семена";
                    else
                        chbParam.Text = "Уруғ";

                    if (cultID > 0 && chbCulture.Checked)
                    {
                        FillSeed();
                    }
                    rbProtectionTypeBio.Visible = rbProtectionTypeJH.Visible = false;
                    break;
                case ReportType.UseFertilizer:
                    if (InformationClass.Lang)
                        chbParam.Text = "Удобрения";
                    else
                        chbParam.Text = "Ўғит";
                    cbParam.DataSource = UtilClass.FillCBCategory(catFertilizer);
                    rbProtectionTypeBio.Visible = rbProtectionTypeJH.Visible = false;
                    break;
                case ReportType.UseProtection:
                    if (InformationClass.Lang)
                        chbParam.Text = "Средства защиты";
                    else
                        chbParam.Text = "Ҳимоя тури";
                    rbProtectionTypeBio.Visible = rbProtectionTypeJH.Visible = true;
                    FillProtection();
                    break;
                default:
                    rbProtectionTypeBio.Visible = groupBoxParam.Visible = rbProtectionTypeJH.Visible = false;
                    break;
            }
            cbParam.DisplayMember = "Name";
            cbParam.ValueMember = "ID";
            cbParam.SelectedIndex = -1;
            cbParam.Text = string.Empty;
            cbParam.SelectedIndexChanged += new EventHandler(cbParam_SelectedIndexChanged);
        }

        private void cbParam_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbParam.SelectedIndex >= 0)
            {
                paramID = Convert.ToInt32(cbParam.SelectedValue);
            }
            else
                paramID = -1;
        }

        private void rbProtectionTypeJH_CheckedChanged(object sender, EventArgs e)
        {
            FillProtection();
        }

        void FillProtection()
        {
            if (InformationClass.Lang)
                cbParam.DataSource = DBClass.PlantProtection
                    .Where(wh => wh.ProtectionType == rbProtectionTypeJH.Checked)
                    .Select(se => new
                    {
                        ID = se.ID,
                        Name = se.Name
                    }).ToArray();
            else
                cbParam.DataSource = DBClass.PlantProtection
                    .Where(wh => wh.ProtectionType == rbProtectionTypeJH.Checked)
                    .Select(se => new
                    {
                        ID = se.ID,
                        Name = se.NameUz
                    }).ToArray();
        }

        void FillSeed()
        {
            if (InformationClass.Lang)
                cbParam.DataSource = DBClass.Seeds
                    .Where(wh => wh.CultureID == cultID)
                    .Select(se => new
                    {
                        ID = se.ID,
                        Name = se.Name
                    }).ToArray();
            else
                cbParam.DataSource = DBClass.Seeds
                .Where(wh => wh.CultureID == cultID)
                .Select(se => new
                {
                    ID = se.ID,
                    Name = se.Name
                }).ToArray();
        }

        private void chbPFSH_CheckedChanged(object sender, EventArgs e)
        {
            groupBox1.Enabled = chbPFSH.Checked;
        }

        private void chbDate_CheckedChanged(object sender, EventArgs e)
        {
            dtpDate.Enabled = chbDate.Checked;
            dtpDate_e.Enabled = chbDate.Checked;
        }

        private void chbParam_CheckedChanged(object sender, EventArgs e)
        {
            cbParam.Enabled = chbParam.Checked;
        }

        private void chbCulture_CheckedChanged(object sender, EventArgs e)
        {
            cbCulture.Enabled = chbCulture.Checked;
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbFH.DataSource = null;
                cbPFSH.DataSource = null;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                cbFH.SelectedIndexChanged -= cbFH_SelectedIndexChanged;
                cbFH.Enabled = true;
                cbFH.DataSource = DBClass.Farms
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbFH.DisplayMember = "Name";
                cbFH.ValueMember = "ID";
                cbFH.SelectedIndex = -1;
                cbFH.Text = string.Empty;
                cbPFSH.DataSource = null;
                cbFH.SelectedIndexChanged += new EventHandler(cbFH_SelectedIndexChanged);
            }
        }

        private void cbFH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbFH.SelectedIndex >= 0)
            {
                fhID = Convert.ToInt32(cbFH.SelectedValue);
                cbPFSH.Enabled = true;
                cbPFSH.SelectedIndexChanged -= cbPFSH_SelectedIndexChanged;
                cbPFSH.DataSource = DBClass.Schools
                    .Where(wh => wh.FarmID == fhID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbPFSH.DisplayMember = "Name";
                cbPFSH.ValueMember = "ID";
                cbPFSH.SelectedIndex = -1;
                cbPFSH.Text = string.Empty;
                cbPFSH.SelectedIndexChanged += new EventHandler(cbPFSH_SelectedIndexChanged);
            }
        }

        private void cbPFSH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbPFSH.SelectedIndex >= 0)
            {
                pfshID = Convert.ToInt32(cbPFSH.SelectedValue);
            }
            else
            {
                pfshID = 0;
            }
        }

        private void cbCulture_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCulture.SelectedIndex >= 0)
            {
                cultID = Convert.ToInt32(cbCulture.SelectedValue);
                if (repType == ReportType.UseSeed)
                {
                    FillSeed();
                    cbParam.SelectedIndex = -1;
                    cbParam.Text = string.Empty;
                }
            }
            else
                cultID = 0;
        }
        int? schID_p, cID_p, pID_p;
        DateTime? dt_p, dte_p;
        private void AddColumn()
        {
            string name = "mounting";
            string header = InformationClass.Lang ? "Нарастающий" : "Ошиб бориши";
            dgvReport.Columns.Add(name, header);
            dgvReport.Columns[name].DisplayIndex = dgvReport.ColumnCount - 1;

            if (dgvReport.RowCount > 0)
                AddData();
        }
        private void AddData()
        {
            for (int rowInd = 0; rowInd < dgvReport.RowCount; rowInd++)
            {
                float v1;
                float v2;
                v1 = float.Parse(dgvReport[5, rowInd].Value.ToString());
                v2 = float.Parse(dgvReport[4, rowInd].Value.ToString());
                dgvReport["mounting", rowInd].Value = v1*v2;
            }
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            int? schID, cID, pID;
            DateTime? dt,dte;

            dgvReport.Columns.Clear();
            dgvReport.DataSource = null;
            

            if (chbPFSH.Checked && pfshID > 0)
                schID = pfshID;
            else
                schID = null;
            schID_p = schID;
            if (chbCulture.Checked && cultID > 0)
                cID = cultID;
            else
                cID = null;
            cID_p = cID;
            if (chbDate.Checked)
            {
                dt = dtpDate.Value.Date;
                dte = dtpDate_e.Value.Date;
            }
            else
            {
                dt = null;
                dte = null;
            }
            dt_p = dt;
            dte_p = dte;
            if (groupBoxParam.Visible  && paramID > 0)
                pID = paramID;
            else
                pID = null;
            pID_p = pID;
            switch (repType)
            {
                case ReportType.UseMechWork:
                    //dgvReport.DataSource = DBClass.RESPContext.MechWorkReport(InformationClass.Lang, schID, cID, dt);
                    dgvReport.DataSource = resp_data.MechWorkReport_n(InformationClass.Lang, schID, cID, dt,dte);

                    break;
                case ReportType.UseHandWork:
                    //dgvReport.DataSource = DBClass.RESPContext.HandWorkReport(InformationClass.Lang, schID, cID, dt);
                    dgvReport.DataSource = resp_data.HandWorkReport_n(InformationClass.Lang, schID, cID, dt, dte);
                    break;
                case ReportType.UseSeed:
                    //dgvReport.DataSource = DBClass.RESPContext.SchoolSeedReport(InformationClass.Lang, schID, pID, dt);
                    //if (CheckParam_seed(schID, cID, pID, dt, dte))
                    //{
                    //    return;
                    //}
                    dgvReport.DataSource = resp_data.SchoolSeedReport_n(InformationClass.Lang, schID, pID, dt, dte);
                    //AddColumn();
                    break;
                case ReportType.UseFertilizer:
                    //dgvReport.DataSource = DBClass.RESPContext.SchoolFertilizerReport(InformationClass.Lang, schID, cID, pID, dt);
                    dgvReport.DataSource = resp_data.SchoolFertilizerReport_n(InformationClass.Lang, schID, cID, pID, dt,dte);
                    //AddColumn();
                    break;
                case ReportType.UseProtection:
                    //dgvReport.DataSource = DBClass.RESPContext.SchoolProtectionReport(InformationClass.Lang, schID, cID, pID, dt);
                    dgvReport.DataSource = resp_data.SchoolProtectionReport_n(InformationClass.Lang, schID, cID, pID, dt,dte);
                    break;
                case ReportType.UseWater:
                    //dgvReport.DataSource = DBClass.RESPContext.SchoolWaterReport(InformationClass.Lang, schID, cID, dt);
                    dgvReport.DataSource = resp_data.SchoolWaterReport_n(InformationClass.Lang, schID, cID, dt,dte);
                    break;
                default:
                    dgvReport.DataSource = null;
                    break;
            }

            GridSettings();
        }
        private Boolean CheckParam_seed(int? schId, int? cId, int? pId, DateTime? dt, DateTime? dte)
        {
            if (schId == null)
            {
                MessageBox.Show(msgClass.msgNoPFS);
                return true;
            }
            if (cId == null)
            {
                MessageBox.Show(msgClass.msgNoCulture);
                return true;
            }
            if (pId == null)
            {
                MessageBox.Show(msgClass.msgNoSeed);
                return true;
            }
            if (dt == null)
            {
                MessageBox.Show(msgClass.msgNoDateStart);
                return true;
            }
            if (dte == null)
            {
                MessageBox.Show(msgClass.msgNoDateStop);
                return true;
            }
            return false; 
        }
        private Boolean CheckParam_culture(int? schId, int? cId, DateTime? dt, DateTime? dte)
        {
            if (schId == null)
            {
                MessageBox.Show(msgClass.msgNoPFS);
                return true;
            }
            if (cId == null)
            {
                MessageBox.Show(msgClass.msgNoCulture);
                return true;
            }
            if (dt == null)
            {
                MessageBox.Show(msgClass.msgNoDateStart);
                return true;
            }
            if (dte == null)
            {
                MessageBox.Show(msgClass.msgNoDateStop);
                return true;
            }
            return false;
        }
        private void GridSettings()
        {
            if (dgvReport.DataSource != null)
            {
                if (dgvReport.Columns.Contains("Name"))
                    dgvReport.Columns["Name"].HeaderText = InformationClass.Lang ? "ПФШ" : "ДФМ";

                if (dgvReport.Columns.Contains("Date"))
                    dgvReport.Columns["Date"].HeaderText = InformationClass.Lang ? "Дата" : "Сана";

                if (dgvReport.Columns.Contains("Area"))
                    dgvReport.Columns["Area"].HeaderText = InformationClass.Lang ? "Площадь" : "Майдон";

                if (dgvReport.Columns.Contains("CultureName"))
                    dgvReport.Columns["CultureName"].HeaderText = InformationClass.Lang ? "Культура" : "Экин тури";

                if (dgvReport.Columns.Contains("SeedName"))
                    dgvReport.Columns["SeedName"].HeaderText = InformationClass.Lang ? "Семена" : "Уруғ";

                if (dgvReport.Columns.Contains("SeedName"))
                    dgvReport.Columns["SeedName"].HeaderText = InformationClass.Lang ? "Семена" : "Уруғ";

                if (dgvReport.Columns.Contains("Operation"))
                    dgvReport.Columns["Operation"].HeaderText = InformationClass.Lang ? "Наименование операции" : "Бажариладиган иш номи";

                if (dgvReport.Columns.Contains("TechKind"))
                    dgvReport.Columns["TechKind"].HeaderText = InformationClass.Lang ? "Вид техники" : "Механизм, трактор маркаси ва номи";

                if (dgvReport.Columns.Contains("Tool"))
                    dgvReport.Columns["Tool"].HeaderText = InformationClass.Lang ? "Орудие" : "Қурол-аслаҳа маркаси ва номи";

                if (dgvReport.Columns.Contains("Dimension"))
                    dgvReport.Columns["Dimension"].HeaderText = InformationClass.Lang ? "Ед. измерения" : "Ўлчов бирлиги";

                if (dgvReport.Columns.Contains("HourQuantity"))
                {
                    if (repType == ReportType.UseMechWork)
                        dgvReport.Columns["HourQuantity"].HeaderText = InformationClass.Lang ? "Количество маш.часов" : "Маш/соатлар сони";
                    else
                        dgvReport.Columns["HourQuantity"].HeaderText = InformationClass.Lang ? "Количество чел.часов" : "Киши/кунлар сони";
                }

                if (dgvReport.Columns.Contains("HourCost"))
                    dgvReport.Columns["HourCost"].HeaderText = InformationClass.Lang ? "Цена часа" : "Бир соатнинг миллий валютадаги нарҳи , сўм";

                if (dgvReport.Columns.Contains("OperationCost"))
                    dgvReport.Columns["OperationCost"].HeaderText = InformationClass.Lang ? "Стоимость операции" : "Бажариладиган ишнинг миллий валютадаги умумий нарҳи, сўм";

                if (dgvReport.Columns.Contains("Cost"))
                    dgvReport.Columns["Cost"].HeaderText = InformationClass.Lang ? "Стоимость" : "Бажариладиган ишнинг миллий валютадаги умумий нарҳи, сўм";

                if (dgvReport.Columns.Contains("Quantity"))
                    dgvReport.Columns["Quantity"].HeaderText = InformationClass.Lang ? "Количество" : "Сони";

                if (dgvReport.Columns.Contains("AllCost"))
                    dgvReport.Columns["AllCost"].HeaderText = InformationClass.Lang ? "Стоимость,сум" : "Бажариладиган ишнинг миллий валютадаги умумий нарҳи, сўм";
                if (dgvReport.Columns.Contains("CostPerHa"))
                    dgvReport.Columns["CostPerHa"].HeaderText = InformationClass.Lang ? "Плата в АВП за 1 га в год" : "Бажариладиган ишнинг миллий валютадаги умумий нарҳи, сўм";

                if (dgvReport.Columns.Contains("Fertilizer"))
                    dgvReport.Columns["Fertilizer"].HeaderText = InformationClass.Lang ? "Удобрение" : "Ўғитлар";

                if (dgvReport.Columns.Contains("Measure"))
                    dgvReport.Columns["Measure"].HeaderText = InformationClass.Lang ? "Ед. измерения, тыс.м3" : "Ўлчов бирлиги, тыс.м3";

                if (dgvReport.Columns.Contains("IrrPurpose"))
                    dgvReport.Columns["IrrPurpose"].HeaderText = InformationClass.Lang ? "Назначение полива" : "Суғоришдан мақсад";

                if (dgvReport.Columns.Contains("WaterQuantity"))
                    dgvReport.Columns["WaterQuantity"].HeaderText = InformationClass.Lang ? "Количество воды" : "Сув миқдори";
                if (dgvReport.Columns.Contains("WaterQuantityPerHa"))
                    dgvReport.Columns["WaterQuantityPerHa"].HeaderText = InformationClass.Lang ? "Удельная водоподача на 1 га, тыс.м³" : "Сув миқдори";

                if (dgvReport.Columns.Contains("Price"))
                    dgvReport.Columns["Price"].HeaderText = InformationClass.Lang ? "Цена" : "нарҳи";
                if (dgvReport.Columns.Contains("PriceWater"))
                    dgvReport.Columns["PriceWater"].HeaderText = InformationClass.Lang ? "Цена за 1 тыс.м3 в сум" : "нарҳи";
                if (dgvReport.Columns.Contains("PricePerKg"))
                    dgvReport.Columns["PricePerKg"].HeaderText = InformationClass.Lang ? "Цена за 1 кг в сум" : "нарҳи";

                if (dgvReport.Columns.Contains("ProtectioinName"))
                    dgvReport.Columns["ProtectioinName"].HeaderText = InformationClass.Lang ? "Вид защиты" : "Ҳимоя тури";

                dgvReport.AutoResizeColumns();
            }

        }

        private void dgvReport_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvReport.Columns.Contains("Operation"))
            {
                if (e.ColumnIndex.Equals(dgvReport.Columns["Operation"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, catOperation);
                }
            }
            if (dgvReport.Columns.Contains("Date"))
            {
                if (e.ColumnIndex.Equals(dgvReport.Columns["Date"].Index) && e.Value != null)
                {
                    DateTime c_date;
                    //c_date = DateTime.Parse(dgvReport["Date", rowInd].Value.ToString());
                    c_date = (DateTime)e.Value;
                    if (c_date.Year > 2040)
                    {
                        e.Value =InformationClass.Lang ? "Итого" : "Жами";
                    }
                }
            }

            if (dgvReport.Columns.Contains("TechKind"))
            {
                if (e.ColumnIndex.Equals(dgvReport.Columns["TechKind"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, catTechniqe);
                }
            }

            if (dgvReport.Columns.Contains("Tool"))
            {
                if (e.ColumnIndex.Equals(dgvReport.Columns["Tool"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, catTechTool);
                }
            }
            if (dgvReport.Columns.Contains("Dimension"))
            {
                if (e.ColumnIndex.Equals(dgvReport.Columns["Dimension"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, catDimension);
                }
            }

            if (dgvReport.Columns.Contains("ProtectioinName"))
            {
                if (e.ColumnIndex.Equals(dgvReport.Columns["ProtectioinName"].Index) && e.Value != null)
                {
                    //if (InformationClass.Lang)
                    //    e.Value = DBClass.PlantProtection.Where(wh => wh.ID == (int)e.Value).Select(se => se.Name).SingleOrDefault();
                    //else
                    //    e.Value = DBClass.PlantProtection.Where(wh => wh.ID == (int)e.Value).Select(se => se.NameUz).SingleOrDefault();
                }
            }
            if (dgvReport.Columns.Contains("Fertilizer"))
            {
                if (e.ColumnIndex.Equals(dgvReport.Columns["Fertilizer"].Index) && e.Value != null)
                {
                    e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, catFertilizer);
                }
            }

            if (dgvReport.Columns.Contains("Cost") ||
                dgvReport.Columns.Contains("OperationCost") ||
                dgvReport.Columns.Contains("Price") ||
                dgvReport.Columns.Contains("HourCost") ||
                dgvReport.Columns.Contains("Area") ||
                dgvReport.Columns.Contains("AllCost"))
            {
                switch (dgvReport.Columns[e.ColumnIndex].Name)
                {
                    case "Cost":
                    case "OperationCost":
                    case "Price":
                    case "HourCost":
                    case "Area":
                        if (e.Value != null)
                        {
                            e.Value = ((decimal)e.Value).ToString("N2");
                        }
                        break;
                    case "AllCost":
                        if (e.Value != null)
                        {
                            e.Value = ((decimal)e.Value).ToString("N2");
                        }
                        break;
                    default:
                        break;
                }

                //if ((e.ColumnIndex.Equals(dgvReport.Columns["Cost"].Index) ||
                //    e.ColumnIndex.Equals(dgvReport.Columns["OperationCost"].Index) ||
                //    e.ColumnIndex.Equals(dgvReport.Columns["Price"].Index) ||
                //    e.ColumnIndex.Equals(dgvReport.Columns["HourCost"].Index) ||
                //    e.ColumnIndex.Equals(dgvReport.Columns["HourCost"].Index)) && e.Value != null)
                //{

                //}
            }

        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvReport.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();

                excelapp.Visible = true;
            }
        }

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            string repFile = string.Empty;

            switch (repType)
            {
                case ReportType.UseMechWork:
                    repFile = InformationClass.Lang ? "i13r15.xls" : "i13r15uz.xls";
                    break;
                case ReportType.UseHandWork:
                    repFile = InformationClass.Lang ? "i14r16.xls" : "i14r16uz.xls";
                    break;
                case ReportType.UseSeed:
                    repFile = InformationClass.Lang ? "i15.xls" : "i15uz.xls";
                    break;
                case ReportType.UseFertilizer:
                    repFile = InformationClass.Lang ? "i16.xls" : "i16uz.xls";
                    break;
                case ReportType.UseProtection:
                    repFile = InformationClass.Lang ? "i20.xls" : "i20uz.xls";
                    break;
                case ReportType.UseWater:
                    repFile = InformationClass.Lang ? "i17.xls" : "i17uz.xls";
                    break;
                default:
                    return;
                    break;
            }


            excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\" + repFile, false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            int head_size=1;
            int left = 0, top = 0, col = 0;
            Rpoints rpnts=new Rpoints();
            Rpoints rpnts_templ=new Rpoints();
            rpnts.top_x = 0;
            sPoint spn=new sPoint();
            Range range_templ;
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);
            excelworksheet.Cells.NumberFormat = "@";
            switch (repType)
            {
                case ReportType.UseMechWork:
                    if (CheckParam_culture(schID_p, cID_p, dt_p, dte_p))
                    {
                        return;
                    }
                    left = 0; top = 11; col = 4;
                    rpnts.top_x = 2;
                    rpnts.top_y = 10;
                    rpnts.bottom_x = 10;
                    rpnts.bottom_y = 11;
                    spn.x = 0;
                    spn.y = 1;
                    rpnts_templ = rpnts;
                    head_size = 1;
                    excelworksheet.Cells[9, 6] = cbCulture.Text;
                    excelworksheet.Cells[9, 9] = dgvReport[3, 0].FormattedValue;
                    break;
                case ReportType.UseHandWork:
                    left = 0; top = 11; col = 4;
                    rpnts.top_x = 2;
                    rpnts.top_y = 10;
                    rpnts.bottom_x = 10;
                    rpnts.bottom_y = 11;
                    spn.x = 0;
                    spn.y = 1;
                    rpnts_templ = rpnts;
                    head_size = 1;
                    excelworksheet.Cells[9, 5] = cbCulture.Text;
                    excelworksheet.Cells[9, 7] = dgvReport[3, 0].FormattedValue;
                    break;
                case ReportType.UseSeed:
                    if (CheckParam_seed(schID_p, cID_p, pID_p, dt_p, dte_p))
                    {
                        return;
                    }
                    left = 1; top = 12; col = 3;
                    rpnts.top_x = 2;
                    rpnts.top_y = 11;
                    rpnts.bottom_x = 10;
                    rpnts.bottom_y = 12;
                    spn.x = 0;
                    spn.y = 1;
                    rpnts_templ = rpnts;
                    head_size = 1;
                    excelworksheet.Cells[9, 5] = cbCulture.Text;
                    excelworksheet.Cells[9, 7] = dgvReport[2, 0].FormattedValue;
                    break;
                case ReportType.UseFertilizer:
                    left = 0; top = 11; col = 4;
                    rpnts.top_x = 2;
                    rpnts.top_y = 10;
                    rpnts.bottom_x = 10;
                    rpnts.bottom_y = 11;
                    spn.x = 0;
                    spn.y = 1;
                    rpnts_templ = rpnts;
                    head_size = 1;
                    excelworksheet.Cells[9, 5] = cbCulture.Text;
                    excelworksheet.Cells[9, 7] = dgvReport[3, 0].FormattedValue;
                    break;
                case ReportType.UseProtection:
                    left = 4; top = 11; col = 5;
                    rpnts.top_x = 2;
                    rpnts.top_y = 10;
                    rpnts.bottom_x = 10;
                    rpnts.bottom_y = 11;
                    spn.x = 0;
                    spn.y = 1;
                    rpnts_templ = rpnts;
                    head_size = 1;
                    excelworksheet.Cells[9, 5] = cbCulture.Text;
                    excelworksheet.Cells[9, 7] = dgvReport[3, 0].FormattedValue;
                    break;
                case ReportType.UseWater:
                    left = 4; top = 11; col = 4;
                    rpnts.top_x = 2;
                    rpnts.top_y = 10;
                    rpnts.bottom_x = 10;
                    rpnts.bottom_y = 11;
                    spn.x = 0;
                    spn.y = 1;
                    rpnts_templ = rpnts;
                    head_size = 1;
                    excelworksheet.Cells[9, 5] = cbCulture.Text;
                    excelworksheet.Cells[9, 9] = dgvReport[3, 0].FormattedValue;
                    break;
                default:
                    break;
            }

            range_templ = MakeExcel.GetRange(excelworksheet, rpnts_templ);

            if (chbPFSH.Checked)
            {
                excelworksheet.Cells[4, 3] = cbRegion.Text;
                excelworksheet.Cells[5, 3] = cbAVP.Text;
                excelworksheet.Cells[6, 3] = cbFH.Text;
                excelworksheet.Cells[7, 3] = cbPFSH.Text;
            }

            if (chbDate.Checked)
            {
                if (dtpDate.Value.Year.ToString() != dtpDate_e.Value.Year.ToString())
                {
                    excelworksheet.Cells[9, 2] = InformationClass.Lang ? "Год: " + dtpDate.Value.Year.ToString() + "-" + dtpDate_e.Value.Year.ToString()
                                                 : "Йил: " + dtpDate.Value.Year.ToString() + "-" + dtpDate_e.Value.Year.ToString();
                }
                if (dtpDate.Value.Year.ToString() == dtpDate_e.Value.Year.ToString())
                {
                    excelworksheet.Cells[9, 2] = InformationClass.Lang ? "Год: " + dtpDate.Value.Year.ToString(): "Йил: " + dtpDate.Value.Year.ToString();
                }
            }
            //if (chbCulture.Checked)
            //{
            //    excelworksheet.Cells[9, 5] = dgvReport[2, beg_row_prev].FormattedValue;
            //}
            int beg_row=0;
            int beg_row_prev = 0;
            //excelworksheet.Cells[9, 5] = dgvReport[2, beg_row].FormattedValue;
            //excelworksheet.Cells[rpnts.bottom_y, 5] = dgvReport[2, beg_row].FormattedValue;
            top = rpnts.bottom_y;
            while (BuildCultureTabl(excelworksheet, dgvReport, head_size,
                                              top, left,ref beg_row, ref rpnts, spn, col) != -1)
            {
                top = rpnts.bottom_y+1;
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Select(1);
        }
        private int BuildCultureTabl(Worksheet excelworksheet, DataGridView dgvReport, int head_size, int top,
                                     int left, ref int beg_row, ref Rpoints rpnts, sPoint spn, int col)
        {
            //if (beg_row != dgvReport.Rows.Count)
            //{
            //    excelworksheet.Cells[rpnts.bottom_y, 5] = dgvReport[2, beg_row].FormattedValue;
            //}
            switch (repType)
            {
                case ReportType.UseMechWork:
                    beg_row = MakeExcel.FillRange(excelworksheet, dgvReport, head_size,
                                                      top, left, beg_row, ref rpnts, spn, col);
                    break;
                case ReportType.UseHandWork:
                    beg_row = MakeExcel.FillRange(excelworksheet, dgvReport, head_size,
                                                      top, left, beg_row, ref rpnts, spn, col);
                    break;
                case ReportType.UseSeed:
                    beg_row = MakeExcel.FillRange_seed(excelworksheet, dgvReport, head_size,
                                                      top, left, beg_row, ref rpnts, spn, col);
                    break;
                case ReportType.UseFertilizer:
                    beg_row = MakeExcel.FillRange_seed(excelworksheet, dgvReport, head_size,
                                                      top, left, beg_row, ref rpnts, spn, col);
                    break;
                case ReportType.UseProtection:
                    beg_row = MakeExcel.FillRange_protection(excelworksheet, dgvReport, head_size,
                                                      top, left, beg_row, ref rpnts, spn, col);
                    break;
                case ReportType.UseWater:
                    beg_row = MakeExcel.FillRange_use(excelworksheet, dgvReport, head_size,
                                                     top, left, beg_row, ref rpnts, spn, col);
                    break;
                default:
                    dgvReport.DataSource = null;
                    break;
            }
            return beg_row;
        }
        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvReport.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvReport);
        }
    }
}
